package com.hongli.blog.controller;

import com.hongli.blog.config.Result;
import com.hongli.blog.config.StringUtils;
import com.hongli.blog.entity.BasicsDao;
import com.hongli.blog.entity.BlogContentDao;
import com.hongli.blog.mapper.Basicsmapper;
import com.hongli.blog.mapper.BlogContentmapper;
import com.hongli.blog.scheduledtask.InitializationController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @Author ZERO
 * @Date 2021/11/12 13:57
 **/
@RestController
@RequestMapping(value = "/Content")
@CrossOrigin
public class ContentController {
    @Autowired
    private BlogContentmapper blogContentmapper;

    private InitializationController INITI = new InitializationController();

    /** 查询所有内容
      * @author ZERO
      * @date 2021/11/12 14:05
    **/
    @GetMapping(value = "/GetContents")
    public Result getContents(){
        //id,content,time
        List<BlogContentDao> blogContentDaoList = blogContentmapper.SelectAllBlogContent();
        if(blogContentDaoList.size() <= 0){
            return Result.fail("1000");
        }
        ArrayList<Object> mapcount = new ArrayList<>();
        for(BlogContentDao b : blogContentDaoList){
            HashMap<String,Object> map = new HashMap<>();
            map.put("blogid",b.getContentid()+7);
            map.put("blogtitle",b.getBlogtitle());
            map.put("blogtime",INITI.Times(b.getBlogdatetime()));
            map.put("blogpicture",b.getBlogpicture());
            mapcount.add(map);
        }
        return Result.fail("2000",mapcount);
    }

    /** 返回内容map
      * @author ZERO
      * @date 2021/11/16 16:17
    **/
    @PostMapping(value = "/PostUserContents")
    public Result getUserContents(@RequestBody Map<String, Object> maps){
        int id = Integer.parseInt(maps.get("use").toString())-7;
        BlogContentDao blogContentDao = blogContentmapper.SelectUserBlogContent(id);
        if(blogContentDao == null) return Result.fail("1000");
        HashMap<String,Object> map = new HashMap<>();
        map.put("titles",blogContentDao.getBlogtitle());
        map.put("times",INITI.Times(blogContentDao.getBlogdatetime()));
        map.put("contents",blogContentDao.getBlogcontent());
        return Result.fail("2000",map);
    }

    /** 重组图片名称返回
      * @author ZERO
      * @date 2021/11/16 17:14
    **/
    @PostMapping(value = "/Postcovers")
    public Result getUpdataPIC(MultipartFile file)throws Exception{
        String[] pic = file.getOriginalFilename().trim().split("\\.");
        if("png".equals(pic[1]) || "PNG".equals(pic[1])
                || "jpg".equals(pic[1]) || "JPG".equals(pic[1])
                || "jpeg".equals(pic[1]) || "JPEG".equals(pic[1])){
            String folder = "D:/spr/X1108/blog-back-end/src/main/resources/static/picimg";
            File imageFolder = new File(folder);
            File f = new File(imageFolder, StringUtils.getRandomString(6) + file.getOriginalFilename()
                    .substring(file.getOriginalFilename().length() - 4));
            if (!f.getParentFile().exists())
                f.getParentFile().mkdirs();
            try {
                file.transferTo(f);
                String imgURL = "http://localhost:7777/Content/file/" + f.getName();
                return Result.fail("2000",imgURL);
            } catch (IOException e) {
                e.printStackTrace();
                return Result.fail("1000");
            }
        }else return Result.fail("3000");
    }

    /** 添加文章
      * @author ZERO
      * @date 2021/11/17 13:58
    **/
    @PostMapping(value = "/InsertblogContent")
    public Result insertBlogContent(@RequestBody Map<String, Object> maps, HttpServletRequest request){
        //2021.11.16：
        // 第一上传图片时无法判断图片格式，它上传的内部自动完成了；
        // 第二上传的图片到后端后格式就乱了；@解：没有关系的，vue会自动帮助我们处理的，只有赋予正确到路径即可
        // 第三前端拿到图片路径但没有处理，要处理后图片才能显示；@解：vue已经帮助我们处理了，它（:src=....）就可以了
        String P = maps.get("P").toString(),
                T = maps.get("T").toString(),
                C = maps.get("C").toString();
        if(P.trim().length() <= 0 || T.trim().length() <= 0 || C.trim().length() <= 0){
            return Result.fail("1000");
        }
        blogContentmapper.insertBlogContent(
                new BlogContentDao(0,INITI.Cookie_Decryption(request),INITI.Processing_Time(),T,C,P));
        return Result.fail("2000","ok");
    }
}
